import { Component } from 'react';

class ErrorBoundary extends Component {
  constructor (props) {
    super(props)
    this.state = {
      hasError: false,
    }
  }

  static getDerivedStateFromError (error) {
    return { hasError: true }
  }

  componentDidCatch(error) {
    console.log(error)
  }

  handleRestry = () => {
    this.setState({ hasError: false })
  }

  render() {
    const { hasError } = this.state
    const { children } = this.props
    if (hasError) {
      return (
        <p>
          <span>对不起 出错了</span>
          <button onClick={this.handleRestry} type="button">please try again</button>
        </p>
      )
    }
    return children()
  }
}

export default ErrorBoundary
